<template>
  <div>
    <PopUps v-if="popFlag" widthMy="60%" height-my="78%">
      <!-- 详细弹窗 -->
      <OrderDetail @closePopUps="closePopUps" :rowDataDetail="rowDataDetail"></OrderDetail>
    </PopUps>
    <PopUps v-if="uptatePop" widthMy="60%" height-my="78%">
      <!-- 修改弹窗 -->
      <OrderUpdate
        @closeUptatePop="closeUptatePop"
        :rowDataUpdate="rowDataUpdate"
        @updataCustomer="updataCustomer"
        @setUserOneInfo="setUserOneInfo"
        @createTable="createTable"
        @deleteRow="deleteRow"
      >
      </OrderUpdate>
    </PopUps>
    <!-- 工单除了利润管理 以及要合并的后续的工单审核 -->
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      :max-height="tableHeight"
      border
      @selection-change="handleSelectionChange"
      style="width: 100%; overflow-y: scroll"
      :header-cell-style="{ color: '#333', background: `#f6f6f6 !important` }"
      @select="handleSelect"
      :row-class-name="tableRowClassName"
    >
      <!--      @cell-dblclick="tableDetail"-->
      <el-table-column type="selection" width="55" :align="'center'" fixed />
      <el-table-column label="单据日期" width="150" :align="'center'" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.orderDate?.slice(0, 10) }}</template>
      </el-table-column>
      <el-table-column
        property="orderId"
        label="单据编号"
        width="170"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column
        property="costingId"
        label="核算编号"
        width="140"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column
        property="deptName"
        label="部门名称"
        width="140"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column label="业务类型" width="120" :align="'center'" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.productionVOS[0]?.businessType }}</template>
      </el-table-column>
      <el-table-column
        property="customerName"
        label="客户名称"
        width="180"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column
        property="customerStore"
        label="终端门店"
        width="140"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column
        property="customerType"
        label="客户类型"
        width="120"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column
        property="productionVOS[0].productName"
        label="存货"
        width="130"
        :align="'center'"
        show-overflow-tooltip
        v-if="isfalse"
      />
      <el-table-column
        property="productionVOS[0].productionContent"
        label="制作内容"
        width="140"
        :align="'center'"
        show-overflow-tooltip
      />
      <!-- <el-table-column property="specs" label="规格型号" width="140" :align="'center'" v-if="isfalse" />
      <el-table-column property="width" label="宽" width="80" :align="'center'" v-if="isfalse" />
      <el-table-column property="height" label="高" width="80" :align="'center'" v-if="isfalse" /> -->
      <el-table-column
        property="productionVOS[0].quantityPerPiece"
        label="件数"
        width="80"
        :align="'center'"
        v-if="isfalse"
        show-overflow-tooltip
      />
      <!-- <el-table-column property="unit" label="单位" width="80" :align="'center'" v-if="isfalse" /> -->
      <el-table-column
        property="productionVOS[0].totalQuantity"
        label="数量"
        width="80"
        :align="'center'"
        v-if="isfalse"
        show-overflow-tooltip
      />
      <el-table-column
        property="productionVOS[0].salePrice"
        label="销售单价"
        width="120"
        :align="'center'"
        v-if="isfalse"
        show-overflow-tooltip
      />
      <el-table-column
        property="productionVOS[0].price"
        label="成本单价"
        width="120"
        :align="'center'"
        v-if="isfalse"
        show-overflow-tooltip
      />
      <el-table-column
        property="totalOrderAmount"
        label="订单总金额"
        width="120"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column label="单据状态" width="120" :align="'center'" show-overflow-tooltip>
        <template #default="scope">
          <p :class="scope.row.invoiceStatus">
            {{ scope.row.invoiceStatus }}
          </p>
        </template>
      </el-table-column>
      <el-table-column label="结款状态" width="120" :align="'center'" show-overflow-tooltip>
        <template #default="scope">
          <p :class="scope.row.paymentStatus">
            {{ scope.row.paymentStatus }}
          </p>
        </template>
      </el-table-column>
      <el-table-column
        property="materialFeeTotal"
        label="材料费合计"
        width="120"
        :align="'center'"
        show-overflow-tooltip
        v-if="isfalse"
      />
      <el-table-column
        property="installationFeeTotal"
        label="工费合计"
        width="120"
        :align="'center'"
        show-overflow-tooltip
        v-if="isfalse"
      />
      <el-table-column
        property="urbanManagementFee"
        label="城管费"
        width="120"
        :align="'center'"
        show-overflow-tooltip
        v-if="isfalse"
      />
      <el-table-column
        property="creator"
        label="制单人"
        width="120"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column
        property="productionVOS[0].outsourcingName"
        label="外协商"
        width="120"
        :align="'center'"
        show-overflow-tooltip
      />
      <el-table-column
        property="setting"
        label="上传合同"
        :align="'center'"
        :width="settingWidth"
        class="column-box"
        fixed="right"
        v-if="props.contractFlag"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            class="table-setting"
            @click="subContractFn(scope.row)"
            v-if="scope.row.invoiceStatus === '待上传合同'"
          >
            <span>提交</span>
          </div>
          <div class="table-setting" v-else-if="scope.row.contractId">
            <span style="color: #00b42a; cursor: no-drop">已提交</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        property="remarks"
        label="明细备注"
        width="200"
        :align="'center'"
        show-overflow-tooltip
        v-if="isfalse"
      />
      <el-table-column
        property="setting"
        label="操作"
        :align="'center'"
        :width="settingWidth"
        class="column-box"
        fixed="right"
      >
        <template #default="scope">
          <div class="table-setting">
            <span
              @click="seeAudit(scope.row)"
              v-if="props.auditFlag"
              v-show="scope.row.invoiceStatus == '待审核' && props.todoBtn && props.detailsCheck"
            >
              审核
            </span>
            <span @click="seeDetail(scope.row)" v-show="props.detailsBtnFlag"> 详情 </span>
            <span
              @click="seeUpdate(scope)"
              v-show="props.detailsBtnFlag && props.auditEdit && props.todoEdit"
            >
              编辑
            </span>
            <!-- <p @click="getdeleteFn(scope)" style="color: #31CA79;">删除</p> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageNum">
      <p></p>
      <Pagination
        :hidden="props.total > 0"
        :total="props.total"
        :pageSizes="pageSize"
        @pagination="handleChange"
        @update:page="updatePage"
        @update:limit="updateLimit"
        :page="page"
        :limit="limit"
      />
    </div>
    <!-- 审核 -->
    <AuditDetails
      v-if="flag"
      @closePopUps="closeAuditDetails"
      :auditData="auditData"
      @searchNewList="searchNewList"
    />

    <newAddContract
      v-if="flags"
      :disabled="disabled"
      @closePopUps="closePopUps"
      :popTitle="popTitle"
      @getoutboundOrderData="getoutboundOrderData"
      :defindFlag="defindFlag"
      :classifyFlag="contract"
      :updateInfoDetail="updateInfoDetail"
      :newAddContractRow="newAddContractRow"
    />
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onUnmounted, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination/index'
import PopUps from '@/components/My/PopUps/index.vue'
import OrderDetail from '@/components/My/OrderDetail/index.vue'
import OrderUpdate from '@/components/My/OrderUpdate/index.vue'
import AuditDetails from '@/views/menu/tickets/components/AuditDetails.vue'
import { getdepartmentsApi, getInfoApi } from '@/api/tickets/index'
import { whenMouth } from '@/utils/date.js'
import newAddContract from '@/views/menu/customer/components/newAddContract'

const { proxy } = getCurrentInstance()
// 修改客户flag
let contract = ref(true)
let flag = ref(false)
// 回显数据
let updateInfoDetail = ref(null)
const newAddContractRow = ref(null)
// 表格
import { ElTable, ElMessage } from 'element-plus'

const emit = defineEmits([
  'handleChange',
  'updateLimitHandler',
  'seeDetail',
  'searchNewListApi',
  'handleSelectionChange',
  'getoutboundOrderData',
])

// 订单详情模态框显示
let popFlag = ref(false)
// 订单修改弹窗
let uptatePop = ref(false)
// 修改工单信息
let rowDataUpdate = ref(null)
// 审核工单信息
let auditData = ref(null)
// 工单详情信息
let rowDataDetail = ref(null)
// 删除对话框
let dialogVisible = ref(false)
// 表格高度
let tableHeight = ref(window.innerHeight - 350)

// 存放删除对应数据的数据
let deleteListData = ref()
let props = defineProps({
  boder: {
    type: Boolean,
    default: false,
    required: false, // 是否必传
  },
  contractFlag: {
    type: Boolean,
    default: false,
    required: false, // 是否必传
  },
  bg: {
    type: String,
    default: '#7386D1',
    required: false, // 是否必传
  },
  tableData: {
    type: Object,
    default: [],
    required: false, // 是否必传
  },
  // 是否展示审核页面
  isfalse: {
    type: Boolean,
    default: true,
    required: false, // 是否必传
  },
  // page 激活的页数
  page: {
    type: Number,
    default: 1,
    required: false, // 是否必传
  },
  // limit 条数
  limit: {
    type: Number,
    default: 10,
    required: false, // 是否必传
  },
  // 总数
  total: {
    type: Number,
    default: 100,
    required: false, // 是否必传
  },
  // 工单操作
  iswidth: {
    type: Boolean,
    default: false,
  },
  // 控制审核显示
  auditFlag: {
    type: Boolean,
    default: true,
  },
  settingWidth: {
    type: String,
    default: '140',
  },
  // 审核是否显示详情修改
  detailsBtnFlag: {
    type: Boolean,
    default: true,
  },
  // 待办工单审核按钮
  todoBtn: {
    type: Boolean,
    default: true,
  },
  // 销货单明细编辑
  auditEdit: {
    type: Boolean,
    default: true,
  },
  // 待办工单编辑
  todoEdit: {
    type: Boolean,
    default: true,
  },
  // 工单审核 审核
  detailsCheck: {
    type: Boolean,
    default: true,
  },
})
const searchNewList = () => {
  flag.value = false
  emit('searchNewListApi')
}
// 获取点击操作的id
let selectID = ref([])
const multipleTableRef = ref()
const multipleSelection = ref([])

// 获取工单详情
const getInfoApiFn = async (v) => {
  let params = {
    id: v,
  }
  let res = await getInfoApi(params)
  console.log(res)
}
// 查看审核
const seeAudit = (list) => {
  // 工单详情数据 （二选一）
  auditData.value = list
  flag.value = true
  // 获取工单详情（二选一）
  // getInfoApiFn("2")
}
// 查看工单详情
const seeDetail = (row) => {
  rowDataDetail.value = row
  popFlag.value = true
}
// 修改工单信息
const seeUpdate = (list) => {
  list.row.deptId = Number(list.row.deptId)
  rowDataUpdate.value = list.row
  uptatePop.value = true

  // let oldTime={}
  //  oldTime.year = rowDataUpdate.value.orderDate.slice(0,4)
  //  oldTime.month = rowDataUpdate.value.orderDate.slice(5,7)

  // if(!whenMouth(oldTime)){
  //     uptatePop.value = true
  // }else{
  //     proxy.$modal.msgWarning('非本月工单不能修改');
  // }
}
const updataCustomer = (e, customerObj) => {
  rowDataUpdate.value.customerId = e
  rowDataUpdate.value.customerName = customerObj.label
}
const setUserOneInfo = (id, lable) => {
  rowDataUpdate.value.employeeId = id
  rowDataUpdate.value.employeeName = lable
}

const createTable = (v) => {
  rowDataUpdate.value.productionVOS.push(v)
}
const deleteRow = (v) => {
  rowDataUpdate.value.productionVOS.splice(v.$index, 1)
}

const flags = ref(false)
const disabled = ref(false)
const popTitle = ref('新增')
const defindFlag = ref(true)
const subContractFn = (v) => {
  flags.value = true
  disabled.value = false
  defindFlag.value = true
  newAddContractRow.value = v
}
// 关闭修改模态框
const closeUptatePop = (flag) => {
  uptatePop.value = flag
  emit('searchNewListApi')
}
// 关闭详情模态框
const closePopUps = (flag) => {
  popFlag.value = false
  flags.value = false
}
// 关闭审核页面
const closeAuditDetails = () => {
  flag.value = false
}
// 当选择项发生变化时会触发该事件
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  emit('handleSelectionChange', multipleSelection.value)
  return 'color:red'
}

// 每页显示条目个数
const pageSize = ref([10, 20, 30, 50])

// 分页器大小  当前分页器
const handleChange = (page, pageSize) => {
  emit('handleChange', { page, pageSize })
}
// 当前页面位置发生变化
const updatePage = (val) => {
  console.log(val, '当前页面位置发生变化')
}
// 条目个数发生变化
const updateLimit = (val) => {
  emit('updateLimitHandler', val)
}

// 拿到选中的行id
const handleSelect = (row) => {
  selectID.value = []
  if (row.length > 0) {
    row.forEach((value, index) => {
      selectID.value.push(value.orderId)
    })
  }
}
// 选中背景色
const tableRowClassName = ({ row, rowIndex }) => {
  let color = ''
  for (let item of selectID.value.values()) {
    if (item === row.orderId) color = 'table-SelectedRow-bgcolor'
  }
  return color
}
// 双击事件
const tableDetail = (row, column) => {
  if (!column.label) return
  seeDetail(row)
}

// 计算材料安装城管费
const stopWatch = watch(
  () => [rowDataUpdate.value?.productionVOS, rowDataUpdate.value?.discount],
  ([val, val1]) => {
    // 材料费
    let materials = 0
    // 总金额
    let moneyAll = 0

    let salePriceAllCopy = 0

    // 实际材料费
    let actualCostSum = 0
    val.forEach((v) => {
      // 面积
      if (v.unit == '平方米' || v.unit == '平方') {
        v.totalQuantity = parseFloat(
          Number(v.width * v.height * Number(v.quantityPerPiece)).toFixed(8),
        )
      }
      if (
        v.unit == '个' ||
        v.unit == '套' ||
        v.unit == '张' ||
        v.unit == '份' ||
        v.unit == '项' ||
        v.unit == '包'
      ) {
        if (!Number.isInteger(Number(v.totalQuantity))) {
          v.classErrorBorder = true
        }
      } else {
        v.classErrorBorder = false
      }
      // 销售金额
      v.amount = Number(Number(v.totalQuantity * v.salePrice).toFixed(2))
      // 成本金额
      v.salePriceAll = Number(Number(v.totalQuantity * v.price).toFixed(2))
      salePriceAllCopy += v.salePriceAll

      // 预算成本
      v.budgetCost = Number((Number(v.materialFee) + Number(v.salePriceAll)).toFixed(2))
      materials += Number(Number(v.materialFee).toFixed(2))
      moneyAll += Number(Number(v.amount).toFixed(2))

      actualCostSum += Number(v.actualCost)
      console.log(actualCostSum)
    })

    // 实际材料费
    rowDataUpdate.value.actualTotalMaterial = actualCostSum

    // 材料费
    rowDataUpdate.value.materialFeeTotal = Number((Number(materials) + salePriceAllCopy).toFixed(2))
    // 总金额
    rowDataUpdate.value.totalOrderAmount = Number((Number(moneyAll) - val1).toFixed(2))
  },
  {
    deep: true,
  },
)

// 上传后获取最新的数据
const getoutboundOrderData = () => {
  flags.value = false
  emit('getoutboundOrderData')
}
onUnmounted(() => {
  stopWatch()
})
onMounted(() => {
  // 监听浏览器屏幕变化展示对应的高度
  window.onresize = () => {
    return (() => {
      tableHeight.value = window.innerHeight - 280
    })()
  }
})
</script>
<style lang="scss" scoped>
.已完结,
.审核通过,
.已收款 {
  color: #069f0b;
}

.设计中,
.审核中 {
  color: #ff8c14;
}

.未完结,
.未收款,
.未付款,
.未结款 {
  color: #eb1313;
}

// 鼠标放上去显示背景颜色
// .el-table {
//     --el-table-row-hover-bg-color: #dfdfdf60 !important;
// }
:deep(.table-setting) {
  display: flex;
  align-items: center;
  justify-content: space-around;

  span {
    cursor: pointer;
    color: #1a48fe;
  }

  .dialogContent {
    display: flex;
    align-items: center;
    justify-content: center;

    .bg {
      background-color: #f0ba47;
      width: 16px;
      height: 16px;
      border-radius: 16px;
      color: #ffffff;
      text-align: center;
      line-height: 16px;
      font-size: 12px;
      margin-right: 5px;
    }
  }
}

:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

:deep(.el-dialog .el-dialog__body) {
  flex: 1;
  overflow: auto;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-button) {
  width: 40px;
  height: 25px;
  font-size: 12px;
}

.is-dark {
  text-align: center;
}

.cell {
  display: flex;
  align-items: center;
  justify-content: center;

  .active {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 23px;
    height: 23px;
    background: linear-gradient(180deg, #e2e7ff 0%, #ffffff 100%);
    border-radius: 4px 4px 4px 4px;
  }
}

.pageNum {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 30px;
}
</style>
<style lang="scss">
.popoverTable {
  padding: 0 !important;
  color: #666666;

  p {
    margin: 0;
    height: 30px;
    line-height: 30px;
    font-size: 14px;

    &:hover {
      background: linear-gradient(180deg, #e2e7ff 0%, #ffffff 100%);
      color: #1947ff;
      border: 1px solid #1947ff;
    }
  }
}
</style>
